<template>
    <div class="user-container">
      <!-- 操作栏 -->
      <div class="user-button">
        <el-button type="primary" icon="Plus" @click="handleAdd">新增用户</el-button>
        <el-button type="danger" icon="Delete" :disabled="!selectedRows.length" @click="handleDelete()">批量删除</el-button>
        <el-button type="warning" icon="Download" @click="handleExport">导出excel</el-button>
        <el-button type="success" icon="Upload" @click="handleInport">导入excel</el-button>
      </div>
  
      <!-- 表格 -->
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="userName" label="用户名" />
        <el-table-column prop="realName" label="真实姓名" />
        <el-table-column prop="roleName" label="所属角色" width="200">
            <template #default="{ row }">
              <el-tag :type="row.roleName === 'admin' ? 'success' : 'warning'">
                {{ row.roleName }}
              </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="balance" label="余额" width="200">
            <template #default="{ row }">
              <el-tag :type="row.balance > 0 ? 'success' : 'danger'">
                {{ safeRound(row.balance) }}
              </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
  
      <!-- 抽屉组件 -->
      <user-drawer
        v-model="drawerVisible"
        :is-edit="isEdit"
        :row-data="currentRow"
        @refresh="fetchData"
      />
      <!-- 导入抽屉组件 start-->
    <import-drawer v-model="importDrawerVisible" @success="fetchData" />
      <!--导入抽屉组件 end-->
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import UserDrawer from './UserDrawer.vue'
  import ImportDrawer from './ImportDrawer.vue';
  import { userMangerApi } from '@/api/user'
  import type { User } from '@/types/user'
  import { safeRound } from '@/utils/numberUtils'
  
  // 导入用户信息抽屉显示状态
  const importDrawerVisible = ref(false);

  // 导入操作
  const handleInport = () => {
    importDrawerVisible.value = true;
  }
  // 表格数据
  const tableData = ref<User[]>([])
  const total = ref(0)
  
  // 查询参数
  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    status: undefined
  })
  
  // 抽屉相关
  const drawerVisible = ref(false)
  const isEdit = ref(false)
  const currentRow = ref<User | null>(null)
  
  // 初始化数据
  onMounted(() => {
    fetchData()
  })
  
  // 获取数据
  const fetchData = async () => {
    const res = await userMangerApi.list(queryParams.value)
    tableData.value = res.data.records
    total.value = res.data.total
  }
  
  // 分页事件
  const handleSizeChange = (val: number) => {
    queryParams.value.pageSize = val
    fetchData()
  }
  
  const handleCurrentChange = (val: number) => {
    queryParams.value.pageNum = val
    fetchData()
  }
  
  // 新增
  const handleAdd = () => {
    isEdit.value = false
    currentRow.value = null
    drawerVisible.value = true
  }
  
  // 编辑
  const handleEdit = (row: User) => {
    isEdit.value = true
    currentRow.value = { ...row }
    drawerVisible.value = true
  }

  // 新增状态
const selectedRows = ref<User[]>([])
  
  // 处理选中行变化
  const handleSelectionChange = (rows: User[]) => {
      selectedRows.value = rows
  }
  // 删除
  const handleDelete = async (id?: number) => {
  try {
    if (!id) {
      // 批量删除逻辑
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的用户')
        return
      }
      
      await ElMessageBox.confirm(
        `确认删除选中的${selectedRows.value.length}个用户？`, 
        '提示', 
        { type: 'warning' }
      )
      
      // 提取ID数组
      const ids = selectedRows.value.map(item => item.id)
      
      // 发送请求
      await userMangerApi.deleteBatch({ ids })
      ElMessage.success('批量删除成功')
    } else {
      // 单个删除逻辑
      await ElMessageBox.confirm('确认删除该用户？', '提示', {
        type: 'warning'
      })
      await userMangerApi.delete(id)
      ElMessage.success('删除成功')
    }
    
    fetchData()
    selectedRows.value = [] // 清空选中状态
  } catch (error) {
    // 取消操作
  }
}

// 导出Excel
const handleExport = async () => {
  try {
    const response = await userMangerApi.exportExcel()
    console.log(response)

    // 处理文件名
    const filename = '用户列表.xlsx'
    
    // 创建下载链接
    const blob = new Blob([response])
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + (error.response?.data?.message || error.message))
  }
}

  </script>
  
  <style scoped lang="scss">
  .user-container {
    padding: 20px;

    .user-button {
        margin-bottom: 20px;
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  </style>